package com.ly.cloud.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;


public class BeanCopyUtils {
	/**
	 * 对象属性的拷贝
	 * @param sourceObj	源对象
	 * @param targetClass 目标对象 class
	 * @return
	 */
	public static <T> T copyBeanProperties(Object sourceObj , Class<T> targetClass) {
		if( sourceObj == null) {
			return null;
		}
		T newObj = null;
		try {
			newObj = targetClass.newInstance();
			BeanUtils.copyProperties(sourceObj, newObj);
			return newObj ;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("转换成"+ targetClass +"出现异常！！");
		}
	}
	
	/**
	 * List<Object> 属性的转换
	 * @param sourceList 源list
	 * @param targetClass 目标对象 class
	 * @return
	 */
	public static <T> List<T> copyListProperties(List sourceList, Class<T> targetClass) {
		if(CollectionUtils.isEmpty(sourceList)) {
			return new ArrayList<>();
		}
		List<T> newList = new ArrayList<>();
		T newObj =  null ;
		try {
			for(Object obj : sourceList) {
				newObj = targetClass.newInstance();
				BeanUtils.copyProperties(obj, newObj);
				newList.add(newObj);
			}
			return newList;
		} catch (Exception e) {
			e.printStackTrace(); 
			throw new RuntimeException("转换成"+ targetClass +"出现异常！！");
		}
	}
}
